package com.easylinkin.linkappapi.elasticsearch.entity;

import lombok.Data;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**

/**
 * @Description: 配置类，传递配置，获取Client 实例
 * @author xuguoqing
 * @version [V1.0, 2020年04月26日]
 * @see  [相关类/方法]
 * @since [产品/模块版本]
 */
@Component
@Data
public class ESconfig {

    @Value("${es.host}")
    private String host;

    @Value("${es.port}")
    private int port;

    @Value("${es.schema}")
    private String schema;

    @Value("${es.connectNum}")
    private Integer connectNum;

    @Value("${es.connectPerRoute}")
    private Integer connectPerRoute;

    @Bean
    public HttpHost httpHost(){
        return new HttpHost(host,port,schema);
    }

    @Bean(initMethod="init",destroyMethod="close")
    public ElsClientBeanFactory getFactory(){
        return ElsClientBeanFactory.build(httpHost(), connectNum, connectPerRoute);
    }

    @Bean
    @Scope("singleton")
    public RestHighLevelClient getRHLClient(){
        return getFactory().getRhlClient();
    }

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(httpHost()).setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder.setConnectTimeout(90000000)
                        .setSocketTimeout(90000000).setConnectionRequestTimeout(500000)).setHttpClientConfigCallback((httpAsyncClientBuilder -> {
                    httpAsyncClientBuilder.disableAuthCaching();//禁用身份验证缓存
                    //显式设置keepAliveStrategy
                    httpAsyncClientBuilder.setKeepAliveStrategy((httpResponse,httpContext) -> TimeUnit.MINUTES.toMillis(3));
                    //显式开启tcp keepalive
                    httpAsyncClientBuilder.setDefaultIOReactorConfig(IOReactorConfig.custom().setSoKeepAlive(true).build());
                    /*httpAsyncClientBuilder.setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(50000).setConnectTimeout(50000).setSocketTimeout(300000)
                            .build());*/
                    return httpAsyncClientBuilder;
                }))
        );
        return client;
    }


}

